package com.multithreading.chart1.interrupte;

/**
 * 当线程维了等待一些特定条件到来时，一般会调用sleep函数
 * wait系列函数或者join函数。比如一个线程调用了Thread.sleep(3000)方法，那么
 * 调用线程会被阻塞，知道3s后才会从阻塞状态变为激活状态。但有可能3s 内条件被满足。如果一直等到3s
 * 后返回有点浪费时间。这时候可以调用线程的interrupt方法。强制sleep方法抛出interruptException
 * 异常而返回，线程恢复到激活状态。
 */
public class InterruptedTest {
    public static void main(String[] args) throws InterruptedException {
        Thread threadOne=new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println("threadOne begin sleep for 2000 seconds");
                    Thread.sleep(200000);
                }catch (InterruptedException e){
                    System.out.println("threadOne is interrupter while sleeping");
                    return;
                }
                System.out.println("threadOne-leaving normally");
            }
        });
        //启动线程
        threadOne.start();
        //确保子线程进入休眠状态
        Thread.sleep(1000);
        //打断子线程休眠，让子线程sleep函数返回
        threadOne.interrupt();
        //等待子线程执行完毕
        threadOne.join();
        System.out.println("main thread is over!");
    }
}
